package com.kaili.basic.service.impl;

import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.kaili.basic.pojo.dto.MdmCompanyQueryDto;
import com.kaili.basic.pojo.entity.MdmCompany;
import com.kaili.basic.pojo.entity.MdmCompanyExport;
import com.kaili.basic.mapper.MdmCompanyMapper;
import com.kaili.basic.service.IMdmCompanyService;
import com.kaili.common.util.Http;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author fzj
 * @since 2018-04-25
 */
@Service
public class MdmCompanyServiceImpl extends ServiceImpl<MdmCompanyMapper, MdmCompany> implements IMdmCompanyService {

    @Autowired
    private MdmCompanyMapper mdmCompanyMapper;

    @Override
    public int addMdmCompany(MdmCompany mdmCompany) {
        try {
            //校验用户数量（帐户表中除admin帐号外其余账号总数<=用户数量）
            Integer user_count = mdmCompany.getUserCount();
            if (user_count > 1000000){
                return 301;
            }

            //校验设备最大接入量
            if (null != mdmCompany.getDeviceCount() ){
                int count  = mdmCompany.getDeviceCount();
                if (count < 0){
                    //更新公司编码使用状况为未使用
                    updateCompanyCodeStatusUnuse(mdmCompany.getCompanyCode());
                    return 17;
                }else if (count > 99999999){
                    //更新公司编码使用状况为未使用
                    updateCompanyCodeStatusUnuse(mdmCompany.getCompanyCode());
                    return 18;
                }
            }
            //判断是否已经存在
            MdmCompany mdmCompany1 = mdmCompanyMapper.getMdmCompanyByKeywords1(mdmCompany);
            if (mdmCompany1 != null) {
                //更新公司编码使用状况为未使用
                updateCompanyCodeStatusUnuse(mdmCompany.getCompanyCode());
                return 7;
            }
        /*//附件的新增

        if (bt != null && bt.length > 0) {
            try {

                String fType = fileType;
                //文件实际名称
                String fileName = UUID.randomUUID().toString().replace("-","")+"."+fileType;
                FastDFSClient client = new FastDFSClient("classpath:fds.properties");
                //获取字节流，
                byte[] in = bt;
                String uploadFile = client.uploadFile(in, fileType);
                //上传图片完毕，创建附件
                GlobalAttchment attchment = new GlobalAttchment();
                attchment.setAttExt(fileType);
                attchment.setAttSize(new Long((long) in.length));
                attchment.setCreatedBy(LoginDetailUtils.getCurrentEmployeeId().longValue());
                attchment.setCreatedTime(new Date());
                attchment.setDataType(2L);
                attchment.setDataId(mdmCompany.getCompanyId().longValue());
                attchment.setRdStatus(1);
                attchment.setRealName(fileName);
                //attchment.setSiteId(newsIssue.getSiteId());
                attchment.setRemark("公司上传logo");
                attchment.setAttachmentPath(uploadFile);
                attachmentMapper.addAttachment(attchment);
            } catch (Exception e) {
                System.out.println("图片上传失败" + e);
                return 77;
            }
        }*/
            return mdmCompanyMapper.addMdmCompany(mdmCompany);
        } catch (Exception e) {
            return 8;
        }
    }

    @Override
    public int updateMdmCompany(MdmCompany mdmCompany) {

        return mdmCompanyMapper.updateMdmCompany(mdmCompany);
    }

    @Override
    public int deleteMdmCompany(MdmCompany mdmCompany) {
        return mdmCompanyMapper.deleteMdmCompany(mdmCompany);
    }

    @Override
    public Page<MdmCompany> getMdmCompanyByKeywords(Page<MdmCompany> page, MdmCompanyQueryDto dto) {
        List<MdmCompany> mdmCompanys = mdmCompanyMapper.getMdmCompanyByKeywords(page, dto);
        return page.setRecords(mdmCompanys);
    }

    @Override
    public List<MdmCompanyExport> queryCompanyExport(MdmCompanyQueryDto dto) {
        return mdmCompanyMapper.queryCompanyExport(dto);
    }

    @Override
    public List<MdmCompany> getCompanyCode() {
        return mdmCompanyMapper.getCompanyCode();
    }

    @Override
    public Integer getCompanyCodeByAuto() {
        return mdmCompanyMapper.getCompanyCodeByAuto();
    }

    @Override
    public void createdCompanyCodeAuto(Map<String,Object> map) {
        mdmCompanyMapper.createdCompanyCodeAuto(map);
    }

    @Override
    public void updateCompanyCodeStatusUsing(Integer companyCode) {
        mdmCompanyMapper.updateCompanyCodeStatusUsing(companyCode);
    }

    @Override
    public void updateCompanyCodeStatusUsed(Integer companyCode) {
        mdmCompanyMapper.updateCompanyCodeStatusUsed(companyCode);
    }

    @Override
    public void updateCompanyCodeStatusUnuse(Integer companyCode) {
        mdmCompanyMapper.updateCompanyCodeStatusUnuse(companyCode);
    }

    @Override
    public MdmCompany getCompanyUrl(Long companyId) {
        return mdmCompanyMapper.getCompanyUrl(companyId);
    }

    @Override
    public String SmsVerificationCode(String phone) {
        //随机生成6位验证码
        String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);

        //请求地址
        String uri = "http://userinterface.vcomcn.com/Opration.aspx";

        //发送验证码
        String pstContent = createSubmitXml(phone,verifyCode);

  /*      String str = String.format("<Group Login_Name=\"%s\" Login_Pwd=\"%s\" InterFaceID=\"0\" OpKind=\"0\">",
                "hzkltxgs", MD5("sqr150610")) + "<E_Time></E_Time>" + "<Item>" + "<Task>" + "<Recive_Phone_Number>"
                + phone + "</Recive_Phone_Number>" + "<Content><![CDATA[您好,欢迎使用凯立中小物流平台,您的手机验证码为:" + verifyCode + ",   " + "若非本人操作,请忽略!" + "]]></Content>"
                + "<Search_ID>1a3a</Search_ID>" + "</Tas k>" + "</Item>" + "</Group>";*/

        System.out.println("qingqiu baowen :" +pstContent);
        System.out.println("qingqiu baowen :" +pstContent);
        //接收状态值
        String state = Http.post(uri, pstContent);
        if (state.equals("00")) {
            System.out.println("提交成功");
            //提交成功就做保存
            return verifyCode;
        } else if (state.equals("01")) {
            System.out.println("帐号或密码错误");
            // return "01";
        } else if (state.equals("02")) {
            System.out.println("帐号欠费");
            // return "02";
        } else if (state.equals("09")) {
            System.out.println("无效的接收号码");
            // return "09";
        } else if (state.equals("10")) {
            System.out.println("网络或系统内部错误");
            //return "10";
        }
        return null; //"12";
    }

    public static String MD5(String encryptContent) {
        String result = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(encryptContent.getBytes());
            byte b[] = md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }

            result = buf.toString().toUpperCase();

        } catch (NoSuchAlgorithmException e) {

        }
        return result;
    }

    // 密码采用md5加密
    public static String createSubmitXml(String phone,String verifyCode) {
        Date now = new Date();
        DateFormat dtFormat = DateFormat.getDateInstance();

        String sendtime = dtFormat.format(now);

        StringBuffer sp = new StringBuffer();
        sp.append(String
                .format("<Group Login_Name=\"%s\" Login_Pwd=\"%s\" InterFaceID=\"0\" OpKind=\"0\">",
                        "hzkltxgs", MD5("sqr150610")));
        sp.append("<E_Time></E_Time>");
        sp.append("<Item>");

        sp.append("<Task>");
        sp.append("<Recive_Phone_Number>" + phone + "</Recive_Phone_Number>");
        sp.append("<Content><![CDATA[您好,欢迎使用凯立中小物流平台,您的手机验证码为:" + verifyCode + ",   " + "1分钟内输入有效,若非本人操作,请忽略! " + "]]></Content>");
        sp.append("<Search_ID>1a3a</Search_ID>");
        sp.append("</Task>");


        sp.append("</Item>");
        sp.append("</Group>");

        return sp.toString();
    }

    @CachePut(value = "verifyCode")
    public String saveVerifyCode(String phone, String code) {
        return code;
    }

    @Cacheable(value = "verifyCode")
    public String getVerifyCode(String phone) {
        return "";
    }


    @Override
    public Integer selectPhone(String phoneNumber) {
        return mdmCompanyMapper.selectPhone(phoneNumber);
    }

    @Override
    public String getImgByKey(String key) {
        return mdmCompanyMapper.getImgByKey(key);
    }
}
